import ctypes
from loguru import logger
import uvicorn
import time
import threading
from fastapi import FastAPI
from multiprocessing import Value
import multiprocessing
import signal
import os

from src.core.process_manager import ProcessManager
from src.core.monitor_manager import MonitorManager
from src.utils.proxy_manager import GlobalProxyManager
from src.core.services.user_monitor import UserMonitor
from src.api.routes import router, init_router_dependencies

# 全局变量
app = FastAPI(redirect_slashes=False)
q = multiprocessing.Queue()
process_manager = None
manager = None

def cleanup():
    """清理所有资源"""
    logger.info("开始清理资源...")
    
    try:
        # 停止监控
        MonitorManager.stop_monitoring()
        
        # 停止所有进程
        if process_manager:
            for process in process_manager.processes:
                try:
                    process.terminate()
                    process.join(timeout=1)  # 减少等待时间
                    if process.is_alive():
                        process.kill()  # 强制结束
                except Exception as e:
                    logger.error(f"停止进程失败: {e}")
        
        # 关闭manager
        if manager:
            manager.shutdown()
        
        logger.info("资源清理完成")
    finally:
        os._exit(0)  # 使用os._exit()强制退出

def signal_handler(signum, frame):
    """处理退出信号"""
    logger.info("收到退出信号，开始关闭程序...")
    cleanup()

def main():
    global process_manager, manager
    
    # 注册信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    try:
        # 初始化共享变量
        start_time = time.time()
        manager = multiprocessing.Manager()
        shared_list = manager.list()
        shared_var = Value(ctypes.c_int, 0)
        
        # 初始化代理
        shared_proxy = manager.Value('s', '')
        proxy_manager = GlobalProxyManager(shared_proxy)
        proxy_manager.get_new_proxy()
        
        # 初始化路由依赖
        init_router_dependencies(q, shared_list)
        app.include_router(router)
        
        # 启动进程
        process_manager = ProcessManager()
        process_manager.start_processes(q, shared_list, shared_var, shared_proxy)
        
        # 启动监控
        MonitorManager.start_monitoring(start_time, shared_var, shared_list)
        
        # 启动用户监控
        user_monitor = UserMonitor()
        user_monitor_thread = threading.Thread(
            target=user_monitor.monitor_user,
            daemon=True
        )
        user_monitor_thread.start()
        
        # 启动 FastAPI
        config = uvicorn.Config(
            app=app,
            host="0.0.0.0",
            port=25508,
            loop="asyncio"
        )
        server = uvicorn.Server(config)
        server.run()
        
    except Exception as e:
        logger.error(f"程序运行错误: {e}")
    finally:
        cleanup()

if __name__ == "__main__":
    main() 